import logging

from crontab import CronTab
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from sqlalchemy import and_
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView

from backend.common.api_response import JsonResponse
from backend.common.common import record_dynamic
from backend.common.common_db import Interface
from backend.models import Lyzd_Interface, Lyzd_Interface_Param, Lyzd_Interface_Header, Lyzd_Interface_Case, \
    Lyzd_Interface_Case_Param, Lyzd_Interface_Case_Check, Sys_Project, Sys_Model, Lyzd_Script
# from backend.serializers import ProjectSerializer, ProjectDeserializer, \
#     ProjectMemberDeserializer
from backend.serializers import LyzdScriptSerializer, Sys_CaseSerializer, Lyzd_InterfaceCase_ActionSerializer, \
    Sys_CaseParamSerializer, Sys_CaseCheckSerializer, Lyzd_InterfaceParamSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。



class LyzdScriptList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        script_name = request.GET.get("script_name")
        script_name_zh = request.GET.get("script_name_zh")
        projectID = request.GET.get("project_id")

        # EcaseGroup = DictionarySelect.query.filter(
        # and_(DictionarySelect.status != "3", DictionarySelect.id == modelExeHistory.case_group)).first()

        """
        project=Sys_Project.objects.filter(status=0)
        model = Sys_Model.objects.filter(status=0)
        project__in=project,model__in=model

        """
        project = Sys_Project.objects.filter(status=0)







        if script_name:
            if script_name_zh:

                if projectID:
                    obi = Lyzd_Script.objects.filter(script_name__contains=script_name,
                                                             case_name_zh__contains=script_name_zh, project=projectID,project__in=project).order_by(
                        "-id")
                else:

                    obi = Lyzd_Script.objects.filter(script_name__contains=script_name,
                                                             case_name_zh__contains=script_name_zh,project__in=project).order_by("-id")


            else:  # interfaceID 不存在
                if projectID:
                    obi = Lyzd_Script.objects.filter(script_name__contains=script_name,project=projectID,project__in=project).order_by("-id")

                else:
                    obi = Lyzd_Script.objects.filter(script_name__contains=script_name,project__in=project).order_by("-id")



        else:
            if script_name_zh:

                if projectID:
                    obi = Lyzd_Script.objects.filter( script_name_zh__contains=script_name_zh, project=projectID,project__in=project).order_by(
                        "-id")

                else:
                    obi = Lyzd_Script.objects.filter( script_name_zh__contains=script_name_zh,project__in=project).order_by("-id")

            else:  # interfaceID 不存在
                if projectID:
                    obi = Lyzd_Script.objects.filter(project=projectID,project__in=project).order_by("-id")

                else:
                    obi = Lyzd_Script.objects.filter(project__in=project).order_by("-id")

        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数

        try:

            obm = paginator.page(page)

        except PageNotAnInteger:

            obm = paginator.page(1)
        except EmptyPage:

            obm = paginator.page(paginator.num_pages)
        """
        用途前端处理，后端处理的话需要更新2个py文件才可以所以前端处理
        
        """
        serialize = LyzdScriptSerializer(obm, many=True)


        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")








class EditStatusCase(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def post(self, request):

        """查询条件"""
        # 必传参数
        data = JSONParser().parse(request)

        case_id = tuple(data.values())[0]

        status = Lyzd_Interface_Case.objects.filter(id=case_id)

        flag = status[0].delete_flag

        if flag == '0' or flag == False:
            Lyzd_Interface_Case.objects.filter(id=case_id).update(
                delete_flag=1
            )
            return JsonResponse(code="999999", msg="禁用成功")
        elif flag == '1' or flag == True:
            Lyzd_Interface_Case.objects.filter(id=case_id).update(
                delete_flag=0
            )
            return JsonResponse(code="999999", msg="启用成功")

